package FileControl.Source;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import FileControl.FileControl;

public class Sync extends AbstractCopy{

	public static boolean syncFile(File source, File dest) {
		if(!source.exists()) {
			println("Sync Error: source file-> " + source.getName() + " does NOT exist!");
			return false;
		} else if(!dest.exists()) {
			return FileControl.copy(source,dest);
		} else {
			//check date
			if(source.lastModified() > dest.lastModified()) {
				dest.delete();
				return FileControl.copy(source,dest);
			} 
			else {
				return true;
			}
		}
	}
	
	public static boolean syncDir(File source, File dest) {
		List<File> errors = new LinkedList<File>();
		if(!source.exists()) {
			println("Sync Error: source file-> " + source.getName() + " does NOT exist!");
			return false;
		} else if(!source.isDirectory()) {
			println(source.getName() + ": is not a Directory!");
			return false;
		} else if(!dest.exists()) {
			return FileControl.copy(source,dest);
		} else {
			for(File f : source.listFiles()) {
				if(f.isDirectory()) { 
					if(!syncDir(f,new File(dest.getPath() + "/" +f.getName())))
						errors.add(f);
				} else {
					if(!syncFile(f,new File(dest.getPath() + "/" +f.getName())))
						errors.add(f);
				}
			}
			if(errors.size() == 0) {
				return true;
			}
			else {
				println("These files/folders had errors during sync and were NOT copied");
				for(File f : errors) {
					if(f.isDirectory())
						println("\t + " + f.getName());
					else
						println("\t - " + f.getName());
				}
				return false;
			}
		}
	}
}
